package com.juice.iot.sdk.listener;

import com.alibaba.fastjson.JSONObject;
import com.juice.iot.sdk.JuiceClient;
import com.juice.iot.sdk.handler.PropGetHandler;
import com.juice.iot.sdk.protocol.PropGetMessage;
import com.juice.iot.sdk.protocol.PropMessage;
import org.eclipse.paho.client.mqttv3.IMqttMessageListener;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * Created by haonan on 2018/12/27
 *
 * 设备对于云端发起的prop get请求的响应处理
 */
public class PropGetListener implements IMqttMessageListener {

    private final static Logger log = LoggerFactory.getLogger(PropGetListener.class);

    private Map<String,PropGetHandler> handlerMap;

    private JuiceClient juiceClient;

    public PropGetListener(JuiceClient juiceClient,Map<String, PropGetHandler> handlerMap) {
        this.juiceClient = juiceClient;
        this.handlerMap = handlerMap;
    }

    @Override
    public void messageArrived(String topic, MqttMessage message){
        byte[] payload = message.getPayload();
        String msg = new String(payload);
        log.info("receive msg-> topic={} msg={}",topic,msg);
        PropGetMessage msgPropGet = JSONObject.parseObject(msg,PropGetMessage.class);
        if(handlerMap != null){
            String prop = msgPropGet.getFlag();
            PropGetHandler handler = handlerMap.get(prop);
            if(handler != null){
                String value = handler.handle();
                PropMessage propMessage = new PropMessage(msgPropGet.getId(),msgPropGet.getFlag(),value);
                try {
                    juiceClient.propGetReply(propMessage);
                    log.info("get_reply -> {}",propMessage);
                } catch (MqttException e) {
                    log.error("get_reply error",e);
                }
            }else{
                log.error("没有找到属性 {} 对应的处理器",prop);

            }
        }
    }

    public void setHandlerMap(Map<String, PropGetHandler> handlerMap) {
        this.handlerMap = handlerMap;
    }
}
